package com.jianyi.aop;

import com.alibaba.fastjson.JSON;
import com.jianyi.common.IPUtils;
import com.jianyi.common.ShiroUtils;
import com.jianyi.common.SysLogAnnotation;
import com.jianyi.system.model.entity.SysLog;
import com.jianyi.system.service.log.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 系统日志，切面处理类
 *
 */
@Aspect
@Component
public class SysLogAspect {
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	protected HttpServletRequest request;

	@Pointcut("@annotation(com.jianyi.common.SysLogAnnotation)")
	public void logPointCut() {}

	@Before("logPointCut()")
	public void saveSysLog(JoinPoint joinPoint) throws Exception {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLog sysLog = new SysLog();
		SysLogAnnotation syslog = method.getAnnotation(SysLogAnnotation.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		if(args.length != 0){
			String params = JSON.toJSONString(args[0]);
			sysLog.setParams(params);
		}
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));
		sysLog.setRequestUrl(request.getRequestURL().toString());

		//用户
		String principal = ShiroUtils.getPrincipal();
		sysLog.setUsername(String.valueOf(principal));
		//保存系统日志
		sysLogService.save(sysLog);
	}

}
